package com.student.Activitys.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 项目名称：
 * 类描述：屏幕适配拓展类
 * 创建人：张飞祥
 * 创建时间：2017/9/18 下午2:17
 * 修改人：张飞祥
 * 修改时间：2017/9/18 下午2:17
 * 修改备注：
 */
public class UiUtil {
    public static final String TAG = "UiUtil";

    private static int displayWidth = 0; // 显示器宽
    private static int displayHeight = 0; // 显示器高


    public static int getDisplayWidth(Context context) {
        refresh(context);
        return displayWidth;
    }


    public static int getDisplayHeight(Context context) {
        refresh(context);
        return displayHeight;
    }


    private static void refresh(Context context) {
        if (displayWidth > 0 && displayHeight > 0) {
            return;
        }
        init(context);
    }


    private static void init(Context context) {
        try {
            DisplayMetrics dm = new DisplayMetrics();
            WindowManager wm = (WindowManager) context
                    .getSystemService(Context.WINDOW_SERVICE);
            wm.getDefaultDisplay().getMetrics(dm);
            displayWidth = dm.widthPixels;
            displayHeight = dm.heightPixels;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    /**
     * 将px值转换为sp值，保证文字大小不变
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources()
                .getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }


    /**
     * 将sp值转换为px值，保证文字大小不变
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources()
                .getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 获取当前的densityDpi
     */
    public static float getDmDensityDpi(Context context) {
        DisplayMetrics dm = context.getApplicationContext().getResources().getDisplayMetrics();
        float dmDensityDpi = dm.densityDpi;
        return dmDensityDpi;
    }

    /**
     * 适配当前手机代码中设置的px值
     */

    public static int reSizePX(Context context, float pxValue) {
        float XXHDPI = 1080 * 1920;
        int displayWidth = getDisplayWidth(context);
        float scale = 1;
        if (displayWidth <= 720) {
            scale = (float) Math.sqrt(displayWidth * ((float) displayWidth / 720) * 1280 / XXHDPI);
        } else if (displayWidth > 720 && displayWidth < 1440) {
            scale = (float) Math.sqrt(displayWidth * ((float) displayWidth / 1080) * 1920 / XXHDPI);
        } else if (displayWidth >= 1440) {
            scale = (float) Math.sqrt(displayWidth * ((float) displayWidth / 1440) * 2560 / XXHDPI);
        }
        int newPx = (int) (scale * pxValue);
        //        Log.i("UIUtil","width:"+displayWidth+";scale:" + scale+";newPx:"+newPx);
        return newPx;
    }

    /**
     * 修改列表页页签高度宽度
     *
     * @param context
     * @param textView1 当前点击控件高度最高
     * @param textView2 其他控件高度第二
     * @param textView3 其他控件高度第三
     */
    public static void setTabsWH(Context context, TextView textView1, TextView textView2, TextView textView3) {
        LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(reSizePX(context, 250), reSizePX(context, 80));
        LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(reSizePX(context, 226), reSizePX(context, 73));
        LinearLayout.LayoutParams layoutParams3 = new LinearLayout.LayoutParams(reSizePX(context, 206), reSizePX(context, 66));
        layoutParams1.topMargin = reSizePX(context, 30);
        layoutParams2.topMargin = reSizePX(context, 37);
        layoutParams3.topMargin = reSizePX(context, 44);
        textView1.setLayoutParams(layoutParams1);
        textView2.setLayoutParams(layoutParams2);
        textView1.setTextSize(px2sp(context, (float) reSizePX(context, 40)));
        textView2.setTextSize(px2sp(context, (float) reSizePX(context, 38)));
        if (textView3 != null) {
            textView3.setLayoutParams(layoutParams3);
            textView3.setTextSize(px2sp(context, (float) reSizePX(context, 36)));
        }
    }


    /**
     * 获取状态栏高度
     *
     * @param activity
     * @return
     */
    public static int getStatusBarHeight(Activity activity) {
        int result = 0;
        int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = activity.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 加载高清大图的适当缩放功能的方法
     * @param activity
     * @param imagePath
     * @return
     */
    public static Bitmap loadingImageBitmap(Activity activity,String imagePath) {
        /**
         * 获取屏幕的宽与高
         */
        final int width = activity.getWindowManager().getDefaultDisplay().getWidth();
        final int height = activity.getWindowManager().getDefaultDisplay().getHeight();
        /**
         * 通过设置optios来只加载大图的尺寸
         */
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeFile(imagePath, options);
            /**
             * 计算手机宽高与显示大图的宽高，然后确定缩放有比例
             */
            int widthRaio = (int) Math.ceil(options.outWidth/(float)width);
            int heightRaio = (int) Math.ceil(options.outHeight/(float)height);
            if (widthRaio>1&&heightRaio>1){
                if (widthRaio>heightRaio){
                    options.inSampleSize = widthRaio;
                }else {
                    options.inSampleSize = heightRaio;
                }
            }
            /**
             * 设置加载缩放后的图片
             */
            options.inJustDecodeBounds = false;
            bitmap = BitmapFactory.decodeFile(imagePath, options);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bitmap;
    }

    /**
     * 获取控件截图
     *
     * @param v
     * @return
     */
    public static Bitmap loadBitmapFromView(View v) {
        if (v == null) {
            return null;
        }
        Bitmap screenshot;
        screenshot = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.RGB_565);
        Canvas c = new Canvas(screenshot);
        v.draw(c);
        return screenshot;
    }

    /**
     * bitmap 保存到 图库
     * @param context
     * @param bmp
     */
    public static void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ToastUtils.showShort(context, "图片保存成功");
    }
}
